<template>
  <!-- 质量报告模板表单弹窗 -->
  <el-dialog
    v-model="visibleDialog"
    :title="props.title"
    width="1000px"
    draggable
    @close="closeDialog"
  >
    <el-form
      v-show="!props.isReadonly"
      ref="formRef"
      :model="formData"
      :rules="rules"
      label-width="100"
    >
      <el-row>
        <el-col :span="12">
          <el-form-item label="报告类别" prop="reportCategory">
            <el-select
              style="width: 100%"
              v-model="formData.reportCategory"
              placeholder="请选择报告类别"
              clearable
            >
              <el-option
                v-for="item in dictionaryStore.filterDictList('QmsReportType')"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12" />
        <el-col :span="12">
          <el-form-item label="框架名称" prop="reportName">
            <el-input
              v-model="formData.reportName"
              placeholder="请输入框架名称"
              clearable
            />
          </el-form-item>
        </el-col>
        <el-col :span="12" />
        <el-col :span="12">
          <el-form-item label="框架路由" prop="templateRoute">
            <el-input
              v-model="formData.templateRoute"
              placeholder="请输入框架路由"
              clearable
            />
          </el-form-item>
        </el-col>
        <el-col :span="12" />
        <el-col :span="12">
          <el-form-item label="文件编号" prop="fileNo">
            <el-input
              v-model="formData.fileNo"
              placeholder="请输入文件编号"
              clearable
            />
          </el-form-item>
        </el-col>
        <el-col :span="12" />
        <el-col :span="12">
          <el-form-item label="记录流水号" prop="recordSeriesNo">
            <el-input
              v-model="formData.recordSeriesNo"
              placeholder="请输入记录流水号"
              clearable
            />
          </el-form-item>
        </el-col>
        <el-col :span="12" />
        <el-col :span="12">
          <el-form-item label="是否启用" prop="enabled">
            <el-radio-group v-model="formData.enabled">
              <el-radio :label="1">是</el-radio>
              <el-radio :label="0">否</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>

      <h4 class="mb-[20px] mt-[20px]">详细数据</h4>

      <el-card shadow="never" class="table-container">
        <template #header>
          <el-button type="success" plain @click="handleAdd">
            <i-ep-plus />
            新增</el-button
          >
        </template>
        <div class="formTable">
          <el-table
            :data="formData.details"
            style="width: 100%"
            max-height="300"
            :key="Math.random"
            border
          >
            <el-table-column
              type="index"
              label="序号"
              align="center"
              width="80"
            />
            <el-table-column label="编号" props="code" min-width="150">
              <template #default="{ $index, row }">
                <el-form-item
                  :prop="'details.' + $index + '.code'"
                  :rules="rules.code"
                  label-width="0"
                >
                  <el-input
                    v-if="!props.isReadonly"
                    v-model="row.code"
                    placeholder="请输入编号"
                    clearable
                  />
                  <span v-else>{{ row.code }}</span>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column label="名称" props="name" min-width="150">
              <template #default="{ $index, row }">
                <el-form-item
                  :prop="'details.' + $index + '.name'"
                  :rules="rules.name"
                  label-width="0"
                >
                  <el-input
                    v-if="!props.isReadonly"
                    v-model="row.name"
                    placeholder="请输入名称"
                    clearable
                  />
                  <span v-else>{{ row.name }}</span>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column label="内容" props="content" min-width="150">
              <template #default="{ $index, row }">
                <el-form-item
                  :prop="'details.' + $index + '.content'"
                  :rules="rules.content"
                  label-width="0"
                >
                  <el-input
                    v-if="!props.isReadonly"
                    v-model="row.content"
                    placeholder="请输入内容"
                    clearable
                  />
                  <span v-else>{{ row.content }}</span>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column
              fixed="right"
              align="center"
              label="操作"
              width="80"
            >
              <template #default="scope">
                <el-button
                  :disabled="formData.details.length < 2"
                  type="danger"
                  link
                  @click.stop="handleDelete(scope.$index)"
                ><i-ep-delete />
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-card>
    </el-form>
    <el-descriptions
      v-show="props.isReadonly"
      class="margin-top"
      title=""
      :column="1"
      size="large"
      border
    >
      <el-descriptions-item>
        <template #label>
          <div class="cell-item">报告类别</div>
        </template>
        <div style="width: 100%; word-break: break-all">
          <span>{{
            dictionaryStore.filterDictName(
              "QmsReportType",
              formData.reportCategory
            )
          }}</span>
        </div>
      </el-descriptions-item>
      <el-descriptions-item>
        <template #label>
          <div class="cell-item">框架名称</div>
        </template>
        <div style="width: 100%; word-break: break-all">
          <span>{{ formData.reportName }}</span>
        </div>
      </el-descriptions-item>
      <el-descriptions-item>
        <template #label>
          <div class="cell-item">框架路由</div>
        </template>
        <div style="width: 100%; word-break: break-all">
          <span>{{ formData.templateRoute }}</span>
        </div>
      </el-descriptions-item>
      <el-descriptions-item>
        <template #label>
          <div class="cell-item">文件编号</div>
        </template>
        <div style="width: 100%; word-break: break-all">
          <span>{{ formData.fileNo }}</span>
        </div>
      </el-descriptions-item>
      <el-descriptions-item>
        <template #label>
          <div class="cell-item">记录流水号</div>
        </template>
        <div style="width: 100%; word-break: break-all">
          <span>{{ formData.recordSeriesNo }}</span>
        </div>
      </el-descriptions-item>
      <el-descriptions-item>
        <template #label>
          <div class="cell-item">是否启用</div>
        </template>
        <div style="width: 100%; word-break: break-all">
          <span>{{
            dictionaryStore.filterDictName("Enabled", formData.enabled)
          }}</span>
        </div>
      </el-descriptions-item>
    </el-descriptions>

    <template #footer>
      <div class="dialog-footer">
        <el-button
          v-if="!props.isReadonly"
          type="primary"
          :loading="loading"
          @click="handleSubmit"
          >确 定</el-button
        >
        <el-button @click="closeDialog">取 消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import request from "@/utils/request";
import { useDictStoreHook } from "@/store/modules/dictionary"; // 引入
const dictionaryStore = useDictStoreHook();

defineOptions({
  name: "QMSQMSREPORTTEMPLATEADDORUPDATE",
  inheritAttrs: false,
});

const emit = defineEmits(["reset-table", "change-visible"]);

const props = defineProps({
  visible: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  title: {
    type: String,
    default: () => {
      return "";
    },
  },
  data: {
    type: Object,
    default: () => {
      return {};
    },
  },
  isReadonly: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
});

const visibleDialog = ref(false);
watch(
  () => props.visible,
  (newVal: boolean) => {
    visibleDialog.value = newVal;
    setTimeout(() => {
      formRef.value.clearValidate();
    }, 50);
  }
);

const rules = reactive({
  reportCategory: [
    { required: true, message: "请选择报告类别", trigger: "change" },
    { min: 1, max: 32, message: "长度在 1 到 32 个字符", trigger: "blur" },
  ],
  reportName: [
    { required: true, message: "请输入框架名称", trigger: "change" },
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  templateRoute: [
    { required: true, message: "请输入框架路由", trigger: "change" },
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  fileNo: [
    { required: true, message: "请输入文件编号", trigger: "change" },
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  recordSeriesNo: [
    { required: true, message: "请输入记录流水号", trigger: "change" },
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  code: [
    { required: true, message: "请输入编号", trigger: "change" },
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  name: [
    { required: true, message: "请输入名称", trigger: "change" },
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  content: [
    { required: true, message: "请输入内容", trigger: "change" },
    { min: 1, max: 255, message: "长度在 1 到 255 个字符", trigger: "blur" },
  ],
  enabled: [],
});

const formRef = ref(ElForm);

let formData = reactive({
  id: "",
  reportCategory: "",
  reportName: "",
  templateRoute: "",
  fileNo: "",
  recordSeriesNo: "",
  version: "",
  remarks: "",
  createTime: "",
  createdUserId: "",
  createdUserName: "",
  lastUpdateTime: "",
  lastUpdatedUserId: "",
  lastUpdatedUserName: "",
  enabled: 1,
  deleted: "",
  details: [{}],
});

watch(
  () => props.data,
  (newVal: any) => {
    formData.id = "";
    if (newVal?.id) {
      const {
        id,
        reportCategory,
        reportName,
        templateRoute,
        fileNo,
        recordSeriesNo,
        version,
        remarks,
        createTime,
        createdUserId,
        createdUserName,
        lastUpdateTime,
        lastUpdatedUserId,
        lastUpdatedUserName,
        enabled,
        deleted,
      } = newVal;
      Object.assign(formData, {
        id,
        reportCategory,
        reportName,
        templateRoute,
        fileNo,
        recordSeriesNo,
        version,
        remarks,
        createTime,
        createdUserId,
        createdUserName,
        lastUpdateTime,
        lastUpdatedUserId,
        lastUpdatedUserName,
        enabled,
        deleted,
      });
      getdetails();
    }
  }
);

/** 关闭表单弹窗 */
function closeDialog() {
  visibleDialog.value = false;
  emit("change-visible", false);
  resetForm();
}

/** 重置表单 */
function resetForm() {
  formRef.value.resetFields();
  formRef.value.clearValidate();
  formData.details = [JSON.parse(JSON.stringify(details))];
  formData.id = "";
  formData.reportCategory = "";
  formData.reportName = "";
  formData.templateRoute = "";
  formData.fileNo = "";
  formData.recordSeriesNo = "";
  formData.version = "";
  formData.remarks = "";
  formData.createTime = "";
  formData.createdUserId = "";
  formData.createdUserName = "";
  formData.lastUpdateTime = "";
  formData.lastUpdatedUserId = "";
  formData.lastUpdatedUserName = "";
  formData.enabled = 1;
  formData.deleted = "";
}

const loading = ref(false);

/** 质量报告模板保存提交 */
function handleSubmit() {
  formRef.value.validate(async (valid: any) => {
    if (valid) {
      loading.value = true;
      const text = formData.id ? "编辑" : "新增";
      await request({
        url: "/qms/qmsreporttemplate/save",
        method: "post",
        data: formData,
      }).finally(() => {
        loading.value = false;
      });
      ElMessage.success(text + `成功`);
      closeDialog();
      emit("reset-table", formData.id);
    }
  });
}

// 组件销毁时调用
onBeforeUnmount(() => {
  visibleDialog.value = false;
  emit("change-visible", false);
});

async function getdetails() {
  let sondetails = await request({
    url: "/qms/qmsreporttemplate/getDetails",
    method: "post",
    data: formData,
  }).finally(() => {
    loading.value = false;
  });
  formData.details = sondetails.data;
}
const details = {
  id: "",
  templateId: "",
  code: "",
  name: "",
  content: "",
  createUserId: "",
  createUserName: "",
  createTime: "",
  lastUpdateUserId: "",
  lastUpdateUserName: "",
  lastUpdateTime: "",
};

/** 添加行 */
const handleAdd = () => {
  let sondata = JSON.parse(JSON.stringify(details));
  formData.details.push(sondata);
};
/** 删除行 */
const handleDelete = (index: any) => {
  formData.details.splice(index, 1);
};

</script>

<style lang="scss" scoped>
h4 {
  font-weight: 400;
  color: #000;
  padding-left: 10px;
  font-size: 14px;
  line-height: 14px;
}
.formTable {
  :deep(.el-form-item) {
    margin-right: 0 !important;
  }
}
:deep(.el-dialog .el-dialog__body) {
  overflow-y: auto;
  height: 65vh;
}
</style>
